package com.hmdp.interceptor;

import com.hmdp.utils.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 登录拦截器， 不检验 (登录，验证码，不需要权限就能访问的页面)， 仅检查Thread中有无用户信息
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //        //获取token 取redis  hash转UserDTO 刷新token
        //        String token = request.getHeader("authorization");
        //        if (StrUtil.isBlank(token)){
        //            response.setStatus(401);
        //            return false;
        //        }
        //        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        //        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(tokenKey);
        //
        //        if (entries.isEmpty()){
        //            response.setStatus(401);
        //            return false;
        //        }
        //        UserDTO user = BeanUtil.fillBeanWithMap(entries,new UserDTO(),false);
        //
        //        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //
        ////        HttpSession session = request.getSession();
        ////        Object user =  session.getAttribute("user");
        ////        if (user==null){
        ////            response.setStatus(401);
        ////            return false;
        ////        }
        //
        //
        //        UserHolder.saveUser(user);

        // 1判断是否需要拦截

        if (UserHolder.getUser() == null) {
            response.setStatus(401);
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        UserHolder.removeUser();
    }
}
